<template>
  <div class="app-container" id="newGood">
    <el-form ref="form" :model="form" label-width="80px">
      <el-form-item label="商品名称">
        <el-input v-model="form.name" class="w500"></el-input>
      </el-form-item>
      <el-form-item label="商品优惠">
        <el-collapse v-if="discountForm.price!=0" v-model="activeDiscount">
          <el-collapse-item :title="discountForm.describe" name="first">
            <div>优惠：{{discountForm.price}}</div>
            <div>优惠时间：{{discountForm.deadTime}}</div>
            <el-button type="primary" @click="EditDiscount">编辑优惠</el-button>
            <el-button type="primary" @click="delDiscount(discountForm.id)">删除优惠</el-button>
          </el-collapse-item>
        </el-collapse>
        <el-button v-else type="primary" @click="editDiscount = true">添加优惠</el-button>
      </el-form-item>
      <el-form-item label="商品分类">
        <el-select v-model="form.classify" placeholder="请选择分类" @change="changeClassify">
          <el-option v-for="item in classifyList" :key="item.id" :label="item.name" :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="商品封面">
        <el-upload class="cover-uploader" action="http://www.jiatingyigou.com:7001/upload/img" :show-file-list="false" :on-success="handleAvatarSuccess"
          :before-upload="beforeImgUpload">
          <img v-if="form.icon" :src="form.icon" class="cover">
          <i v-else class="el-icon-plus cover-uploader-icon"></i>
          </el-upload>
      </el-form-item>
      <el-form-item label="商品价格">
        <el-input placeholder="价格" v-model="form.price" class="price">
          <template slot="append">¥</template>
        </el-input>
      </el-form-item>
      <el-form-item label="商品库存">
        <el-input-number v-model="form.stock" :min="1" :max="99999"></el-input-number>
      </el-form-item>
      <el-form-item label="商品简介">
        <el-input v-model="form.describe" placeholder="请输入简介" class="w500"></el-input>
      </el-form-item>
      <el-form-item label="商品详情">
        <el-tabs type="border-card" class="w500">
          <el-tab-pane label="使用规则" v-if="info.length>0">
            <p>有效日期：
              <el-input v-model="info[0].info" placeholder="请输入有效期" class="w200"></el-input>
            </p>
            <p>费用说明：
              <el-input v-model="info[1].info" placeholder="请输入费用说明：" class="w200"></el-input>
            </p>
            <p>预定说明：
              <el-input v-model="info[2].info" placeholder="请输入预定说明" class="w200"></el-input>
            </p>
            <p>使用说明：
              <el-input v-model="info[3].info" placeholder="请输入使用说明" class="w200"></el-input>
            </p>
            <p>退款说明：
              <el-input v-model="info[4].info" placeholder="请输入退款说明" class="w200"></el-input>
            </p>
          </el-tab-pane>
          <el-tab-pane label="详情信息" v-if="tags.length>0">
            <p v-for="(tag,index) in tags">
              {{tag.type==1?'上网':tag.type==2?'卫浴':tag.type==3?'窗户':tag.type==4?'可住':tag.type==5?'早餐':tag.type==6?'床型':''}}
              <el-select v-if="tag.type!=6&&tag.type!=4" v-model="tag.tag" placeholder="请选择">
                <el-option v-for="item in webStyle[tag.type]" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
              <el-input v-if="tag.type==6" v-model="tag.tag" placeholder="请输入床型" class="w200"></el-input>
              <el-input v-if="tag.type==4" v-model="tag.tag" placeholder="请输入可住几人" class="w200"></el-input>
            </p>
          </el-tab-pane>
        </el-tabs>
      </el-form-item>
      <el-form-item label="详情图片">
        <el-upload class="upload-demo" action="http://www.jiatingyigou.com:7001/upload/img" :before-upload="beforeImgUpload" :on-preview="handlePreview"
          :on-remove="handleRemove" :file-list="imgList" list-type="picture-card" :on-success="handleImgsSuccess">
          <el-button size="small" type="primary">点击上传</el-button>
          <div slot="tip" class="el-upload__tip">只能上传JPG/PNG文件</div>
          </el-upload>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">立即上架</el-button>
        <el-button type="warning" @click="onSubmit">保存</el-button>
        <el-button>取消</el-button>
      </el-form-item>
      <el-dialog title="添加优惠" :visible.sync="editDiscount" size="small">
        <el-row class="tac">
          <el-col :span="25">
            <el-tabs v-model="tabName" type="card" @tab-click="handleClick">
              <el-tab-pane v-for="(item,index) in  dicountType" :key="index" :label="item.title" :name="item.tabName">
                <el-form style="margin-top:20px;" :model="editDiscountForm" ref="editDiscountForm" label-width="100px" class="demo-editDiscountForm">
                  <div class="p20" v-if="item.type==0">
                    <span>{{item.priceType}}</span>
                    <el-input-number :controls="false" v-model="editDiscountForm.price" class="w100"></el-input-number><span>{{item.tipType}}</span>
                    <el-input-number :controls="false" v-model="editDiscountForm.discount" class="w100"></el-input-number>{{item.desc}}
                  </div>
                  <div class="p20" v-if="item.type==1">
                    <span>{{item.priceType}} </span>
                    <el-input-number size="small" v-model="editDiscountForm.discount" :min="1" :max="9"></el-input-number>
                    <span> 折 </span>
                  </div>
                  <el-form-item label="截至时间" required>
                    <div class="block">
                      <el-date-picker v-model="editDiscountForm.deadTime" type="datetime" placeholder="选择日期时间" align="right">
                      </el-date-picker>
                    </div>
                  </el-form-item>
                  <el-form-item>
                    <el-button type="primary" @click="submitForm(item.type)">立即添加</el-button>
                    <el-button @click="resetForm()">重置</el-button>
                  </el-form-item>
                </el-form>
              </el-tab-pane>
            </el-tabs>
          </el-col>
        </el-row>
      </el-dialog>
    </el-form>
  </div>
</template>
<script>
  import { getGoodsInfo, updateGoodsInfo, getClassify, getGoodsImg, updateGoods, addGoods, addGoodsImg, getGoodsSupport, delGoodsDiscount, updateGoodsDiscount, addGoodsDiscount, delGoodsImg } from '@/api/goods'
  import { getToken } from '@/utils/auth'
  export default {
    data() {
      let self = this;
      return {
        webStyle: {
          1: [{
            value: "无",
            label: "无"
          },
          {
            value: "wifi",
            label: "wifi"
          }],
          2: [{
            value: "无",
            label: "无"
          },
          {
            value: "独立",
            label: "独立"
          },
          {
            value: "公共",
            label: "公共"
          }
          ],
          3: [{
            value: "无",
            label: "无"
          },
          {
            value: "有",
            label: "有"
          }
          ],
          5: [{
            value: "无",
            label: "无"
          },
          {
            value: "有",
            label: "有"
          }
          ]

        },
        info: [],
        tags: [],
        activeDiscount: ["first"],
        tabName: "first",
        dicountType: [{
          title: "减价",
          type: 0,
          priceType: "满减规则： 满",
          tipType: "减",
          desc: "元",
          tabName: "first"
        },
        {
          title: "打折",
          type: 1,
          priceType: "折扣规则： 商品折扣为",
          tipType: "折",
          desc: "折",
          tabName: "two"
        }

        ],
        editDiscount: false,
        classify: "",
        selectClassify: false,
        classifyList: [],
        form: {
          id: 0,
          name: "",
          classify: "",
          classifyId: 0,
          price: 0,
          stock: 0,
          type: 0,
          describe: "",
          icon: ""
        },
        discountForm: {
          name: "",
          type: 0,
          price: 0,
          discount: 0,
          deadTime: "",

        },
        editDiscountForm: {
          id: 0,
          name: "",
          type: 0,
          price: 0,
          discount: 0,
          deadTime: "",
        },
        imgList: [],
        isUpdate: false,
        seller_id: 0
      };
    },
    created() {
      let data = this.$route.query.data


      this.$nextTick(() => {
        getClassify(getToken(), 1).then((res) => {
          if (res.classify) {
            this.classifyList = res.classify
            this.seller_id = this.classifyList[0].goods_id
          }

        })

        if (data) {
          data = JSON.parse(data)
          this.form = data

          this.isUpdate = true
          getGoodsImg(this.form.id).then((res) => {
            if (res.status == 1) {

              this.imgList = res.imgs
            }
          })

          getGoodsInfo(this.form.id).then((res) => {
            if (res.message == "ok") {
              if (res.infos.length > 0) {
                this.info = res.infos

              } else {
                this.info = [
                  { id: 0, info: "", goods_id: this.form.id, type: 1 },
                  { id: 0, info: "", goods_id: this.form.id, type: 2 },
                  { id: 0, info: "", goods_id: this.form.id, type: 3 },
                  { id: 0, info: "", goods_id: this.form.id, type: 4 },
                  { id: 0, info: "", goods_id: this.form.id, type: 5 }
                ]
              }
              if (res.tags.length > 0) {
                this.tags = res.tags
              } else {

                this.tags.push({ id: 0, tag: "", goods_id: this.form.id, type: 1 })
                this.tags.push({ id: 0, tag: "", goods_id: this.form.id, type: 2 })
                this.tags.push({ id: 0, tag: "", goods_id: this.form.id, type: 3 })
                this.tags.push({ id: 0, tag: "", goods_id: this.form.id, type: 4 })
                this.tags.push({ id: 0, tag: "", goods_id: this.form.id, type: 5 })
                this.tags.push({ id: 0, tag: "", goods_id: this.form.id, type: 6 })

              }
            }
          })

          getGoodsSupport(this.form.id).then((res) => {
            if (res.supports && res.supports.length > 0) {
              this.discountForm = res.supports[0]
              this.discountForm.deadTime = new Date(this.discountForm.deadTime * 1)
            }
          })
        } else {
          this.info = [
            { id: 0, info: "", goods_id: this.form.id, type: 1 },
            { id: 0, info: "", goods_id: this.form.id, type: 2 },
            { id: 0, info: "", goods_id: this.form.id, type: 3 },
            { id: 0, info: "", goods_id: this.form.id, type: 4 },
            { id: 0, info: "", goods_id: this.form.id, type: 5 }
          ]
          this.tags = [
            { id: 0, tag: "", goods_id: this.form.id, type: 1 },
            { id: 0, tag: "", goods_id: this.form.id, type: 2 },
            { id: 0, tag: "", goods_id: this.form.id, type: 3 },
            { id: 0, tag: "", goods_id: this.form.id, type: 4 },
            { id: 0, tag: "", goods_id: this.form.id, type: 5 }
          ]
        }
      })
    },
    methods: {
      onSubmit() {
        let content = this.form
        content.seller_id = this.seller_id
        let imgs = this.imgList
        var deadTime = new Date(this.discountForm.deadTime).getTime()
        this.discountForm.deadTime = deadTime
        let discount = this.discountForm

        if (this.isUpdate) {
          var goods_id = this.form.id
          this.$confirm("确定要更新商品？", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }).then(() => {
            updateGoods(content, this.info, this.tags).then((res) => {
              if (res.message == "ok") {
                this.$confirm("商品更新成功！", "提示", {
                  confirmButtonText: "确定",
                  type: "warning"
                })
                  .then(() => {
                    this.$router.push({ path: '/goods/all' })
                  })
                  .catch(() => {
                    this.$router.push({ path: '/goods/all' })
                  });
              }
            })
          }).catch(() => {

          })

        } else {
          addGoods(content, discount).then((res) => {
            if (res.status == 1) {
              let goods_id = res.goods_id

              updateGoodsInfo(goods_id, this.info, this.tags, this.imgList).then((resInfo) => {
                if (resInfo.message == "ok") {
                  this.$confirm("商品上传成功，是否继续上传", "提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                  })
                    .then(() => {
                      this.form = {
                        name: "",
                        classify: "",
                        classifyId: 0,
                        price: 0,
                        stock: 0,
                        type: 0,

                        describe: "",
                        icon: ""
                      }
                      this.info = [{ id: 0, info: "", goods_id: this.form.id, type: 1 },
                      { id: 0, info: "", goods_id: this.form.id, type: 2 },
                      { id: 0, info: "", goods_id: this.form.id, type: 3 },
                      { id: 0, info: "", goods_id: this.form.id, type: 4 },
                      { id: 0, info: "", goods_id: this.form.id, type: 5 }
                      ]
                      this.tags = [
                        { id: 0, tag: "", goods_id: this.form.id, type: 1 },
                        { id: 0, tag: "", goods_id: this.form.id, type: 2 },
                        { id: 0, tag: "", goods_id: this.form.id, type: 3 },
                        { id: 0, tag: "", goods_id: this.form.id, type: 4 },
                        { id: 0, tag: "", goods_id: this.form.id, type: 5 }
                      ]
                      this.discountForm = {
                        name: "",
                        type: 0,
                        describe: "",
                        price: 0,
                        date: "",
                      }
                      this.editDiscountForm = {
                        name: "",
                        type: 0,
                        describe: "",
                        price: 0,
                        date: "",
                      }
                      this.imgList = []

                    })
                    .catch(() => {
                      this.$router.push({ path: '/goods/all' })
                    });
                }
              })
            }
          })
        }
      },
      handleRemove(file, fileList) {

        if (this.isUpdate) {

          this.imgList = this.imgList.concat()
          this.$confirm("确定要删除图片？", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }).then(() => {
            delGoodsImg(file.id).then((res) => {
              if (res.status == 1) {
                this.imgList = fileList
                this.$message({
                  type: "success",
                  message: "图片已删除!"
                });
              }
            })
          }).catch(() => {

          })
        }

      },
      handlePreview(file) {
        console.log(file);
      },
      changeClassify(e) {
        if (!isNaN(e)) {
          this.form.classifyId = e
        }
      },
      handleImgsSuccess(res, file) {
        var newImg = {
          goods_id: this.form.id,
          uid: file.raw.uid,
          status: "success",
          url: "http://" + res.data.url,
        }
        if (this.isUpdate) {
          addGoodsImg(newImg).then((res) => {
            if (res.status == 1) {
              newImg.id = res.id
              this.$message({
                type: "success",
                message: "添加新图片成功!"
              });
            }
          })
        }
        this.imgList.push(newImg)

      },
      handleAvatarSuccess(res, file) {
        this.form.icon = "http://" + res.data.url

      },
      beforeImgUpload(file) {
        const isJPG = file.type === "image/jpeg" || file.type === "image/png";
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJPG) {
          this.$message.error("上传图片只能是 JPG/PNG 格式!");
        }
        if (!isLt2M) {
          this.$message.error("上传图片大小不能超过 2MB!");
        }
        return isJPG && isLt2M;
      },
      editClose() {
        this.editDiscountForm = {
          id: 0,
          name: "",
          type: 0,
          describe: "",
          price: 0,
          date: "",
        }
      },
      resetForm() {
        this.editDiscountForm = {
          id: 0,
          name: "",
          type: 0,
          describe: "",
          price: 0,
          date: "",
        }
      },
      submitForm(type) {
        this.editDiscount = false
        if (this.isUpdate) {
          let comfirm = ""
          if (this.discountForm.id) {
            comfirm = this.$confirm("是否确定更新优惠", "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning"
            })
          } else {
            comfirm = this.$confirm("是否确定添加新优惠", "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning"
            })
          }

          comfirm.then(() => {

            let discountForm = this.editDiscountForm

            let deadTime = new Date(discountForm.deadTime).getTime()
            discountForm.type = type
            discountForm.deadTime = deadTime

            discountForm.goods_id = this.form.id

            if (discountForm.price && discountForm.id) {

              updateGoodsDiscount(discountForm).then((res) => {
                if (res.status == 1) {
                  this.discountForm.deadTime = new Date(this.discountForm.deadTime * 1)
                  this.discountForm = this.editDiscountForm
                  this.$message({
                    type: "success",
                    message: "更新成功!"
                  });
                }
              })
            } else if (discountForm.price) {
              addGoodsDiscount(discountForm).then((res) => {
                if (res.status == 1) {
                  this.discountForm.deadTime = new Date(this.discountForm.deadTime * 1)
                  this.discountForm = this.editDiscountForm
                  this.discountForm.id = this.editDiscountForm.id = res.id
                  console.log(this.discountForm)
                  this.$message({
                    type: "success",
                    message: "添加成功!"
                  });
                }
              })
            }
          })
            .catch(() => {

            });
        } else {
          this.discountForm = this.editDiscountForm
          this.discountForm.type = type
        }


      },
      handleClick() {
        this.editDiscountForm = {
          id: 0,
          name: "",
          type: 0,
          describe: "",
          price: 0,
          date: "",
        }

      },
      EditDiscount() {
        this.editDiscount = true
        if (this.discountForm.type == 1) {
          this.tabName = "first"
        } else if (this.discountForm.type == 2) {
          this.tabName = "two"
        } else {
          this.tabName = "first"
        }
        this.editDiscountForm = this.discountForm

      },
      delDiscount(id) {
        this.$confirm("是否要删除优惠？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.discountForm = {
            name: "",
            type: 0,
            describe: "",
            price: 0,
            deadTime: "",
          }
          this.editDiscountForm = {
            name: "",
            type: 0,
            describe: "",
            price: 0,
            deadTime: "",
          }
          if (this.isUpdate) {
            delGoodsDiscount(id).then((res) => {
              if (res.status == 1) {
                this.$message({
                  type: "success",
                  message: "删除成功!"
                });
              }
            })
          } else {
            this.$message({
              type: "success",
              message: "删除成功!"
            });
          }
        }).catch(() => {

        })
      }
    }
  };

</script>
<style>
  #newGood .el-input-group.price {
    width: 150px;
  }
  
  .cover-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  
  .cover-uploader .el-upload:hover {
    border-color: #20a0ff;
  }
  
  .w100 {
    width: 100px;
    padding: 0 10px;
  }
  
  .w200 {
    width: 200px;
  }
  
  .p20 {
    padding: 20px 0;
  }
  
  .cover-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  
  .cover {
    width: 178px;
    height: 178px;
    display: block;
  }
  
  .w500 {
    width: 500px;
  }
</style>